#!/bin/bash
#
# PB138 Task 4 Checker (XQuery)
# created by Tomáš Pitner, April 2011
# version 1.0, jaro 2011
#
# * Put this script into the same directory where the ZIP
#   with all solutions reside.
# * Put also the check-all-task4 and saxon9he.jar here.
# * Make the scripts both executable.
#
# * Run either this for single solution checking:
#   ./check-task4 Some_Student_UCO_blabla.zip [query_file]
#
#   or to check all ZIPs in the current dir:
#   ./check-all-task4 
#
# * The result of the XQuery execution
#   
#
# * Overall results are present in:
#   
#   ok.txt             -- names of ZIPs that were checked OK 
#   bad-zips.txt       -- names of badly zipped ZIP archives
#   missing-files.txt  -- Nonexistent query file
#   errors.txt         -- runnable but contains test errors
#
# * System requirements: 
#   Linux with Java runtime, saxon9he.jar, junit-4.5.jar, 
#   classes.jar, zip/unzip, bash, xmllint
#

CP=$PWD

ZIP_FILE=$1
unzip $ZIP_FILE

if [ "$2" = "" ]; then
QUERY_FILE=contacted-by.xq
else
QUERY_FILE=$2
fi

# ensure there is no MacOS X stuff...
if [ -d "__MACOSX" ]; then
rm -rf "__MACOSX"
fi

# what is the created dir?
TOP="$(ls --group-directories-first|head -n 1)"
DIR="$TOP"

# if exists, change to it
if [ -d "$DIR" ]; then
cd "$DIR"
echo "Processing $PWD..."

# does the required query file exist?
if [ -f "$QUERY_FILE" ]; then

# remove previous results if present
rm -f result.txt

# yes, then process it 
java -cp "$CP/saxon9he.jar" net.sf.saxon.Query -q:$QUERY_FILE -s:address-book.xml -o:contacted-people.xml

# the run junit-based tests
java -cp "$CP/saxon9he.jar:$CP/junit-4.5.jar:$CP/classes.jar" org.junit.runner.JUnitCore cz.muni.fi.pb138.jaro2011.uloha4.XQueryTest >> result.txt

# save the result and generated XML
cat result.txt | tee ../$ZIP_FILE-result.txt
xmllint --format contacted-people.xml > ../$ZIP_FILE-contacted-people.xml

SUCCESS=$(grep "OK (1 test)" result.txt | wc -l)
cd ..

# zip it all
zip -u -r -q $ZIP_FILE "$TOP"/

if [ $SUCCESS = "1" ]; then
	echo "Done OK $ZIP_FILE" >> ok.txt
else 
	echo "Done but test errors $ZIP_FILE" >> errors.txt
fi

else 
	echo "Nonexistent query file"
	echo $ZIP_FILE >> ../missing-files.txt
fi
else
	echo "Badly zipped solution, $DIR does not exist"
	echo $ZIP_FILE >> bad-zips.txt
fi
rm -rf "$TOP"
